/**
 * @description Sogou Cloud Pinyin Extension for Chrome (Chromium) 
 * @author ZHANG Bei(A.K.A Shinjikun(toaru...)), 
 * iTechs Laboratory, ISCAS, China
 * 
 * <a href="http://www.opensource.org/licenses/gpl-2.0.php">GPLv2</a> Licensed
 */
 
var using = localStorage['enabled']=='open';
function setEnabled(enabled) {
	localStorage['enabled'] = enabled ? "open" : "close";
	chrome.browserAction.setIcon({
				path : enabled
						? 'ime_bit-19x19.png'
						: 'ime_bit-grayed-19x19.png'
			});
	chrome.browserAction.setTitle({
				title : enabled ? '禁用搜狗云输入法' : '启用搜狗云输入法'
			});

	var todo = function(windows) {
		for (var i = 0; i < windows.length; i++) {
			for (var j = 0; j < windows[i].tabs.length; j++) {
				setIMEOfTab(windows[i].tabs[j], enabled);
			}
		}
	};

	chrome.windows.getAll({
				populate : true
			}, todo);
}

function setIMEOfTab(tab, enabled) {
	chrome.tabs.sendRequest(tab.id, {
				type : localStorage['enabled']
			}, function(response) {
				if (sendResponse.result == 'error') {
					console.dir(sendResponse.error.stack || sendResponse.error);
				}
			});
}

function toggle() {
	using = !using;
	setEnabled(using);
}

chrome.browserAction.onClicked.addListener(function(tab) {
			toggle();
		});

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
			try {
				if (request.type == 'current-state') {
					sendResponse({
								result : localStorage['enabled']
							});
				} else if (request.type == 'close') {
					if (using) {
						using = false;
						setEnabled(using);
					}
				}
			} catch (e) {
			}
		}, false);

setEnabled(using);
